package com.demo.deal_service.service.impl;

import com.demo.deal_service.dao.DealDao;
import com.demo.deal_service.enums.ResultEnum;
import com.demo.deal_service.model.entity.Order;
import com.demo.deal_service.model.result.ResultEntity;
import com.demo.deal_service.model.entity.Deal;
import com.demo.deal_service.service.DealService;
import com.demo.deal_service.service.ImageService;
import com.demo.deal_service.service.OrderService;
import com.demo.deal_service.util.ImgUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 描述：通过调用dao或远程服务接口来完成商品管理业务，为调用者提供
 * 商品管理相关的业务方法。
 * 创建者：lp
 */
@Service
public class DealServiceImpl implements DealService {
    private static String IMAGE_MODULE = "DEAL";

    //constant: 每页显示记录数
    private static final int PAGE_SIZE = 10;

    //商品的DAO对象
    private final DealDao dealDao;

    //图片service
    private final ImageService imageService;

    //订单service
    private final OrderService orderService;

    /**
     * 构造函数
     *
     * @param dealDao
     */
    public DealServiceImpl(@Autowired DealDao dealDao, @Autowired ImageService imageService, @Autowired OrderService orderService) {
        this.dealDao = dealDao;
        this.imageService = imageService;
        this.orderService = orderService;
    }

    @Override
    public PageInfo<Deal> getDealByPage(int pageNum) {
        return PageHelper
                .startPage(pageNum, PAGE_SIZE)
                .doSelectPageInfo(dealDao::selectAll);
    }

    @Override
    public Deal getDealById(Long id) {
        Deal deal = dealDao.selectById(id);
        if(deal!=null){
            deal.setImageUrl(ImgUtil.getRelativeSrcPath(id));
        }

        return deal;
    }

    @Override
    public List<Deal> getAllDeals() {
        return null;
    }

    @Override
    public ResultEntity addDeal(Deal deal, MultipartFile image) {
        ResultEntity ret = null;
        InputStream imageIn = null;
        int insCnt = 0;
        String srcImgUrl = "";
        //准备生成图
        try {
            deal.setId(dealDao.selectNextKey());
            imageIn = image.getInputStream();
            imageService.storeImage(deal.getId(), imageIn, IMAGE_MODULE);
        } catch (IOException ioe) {
            return new ResultEntity(ResultEnum.EXC_ELSE, "上传文件失败,程序错误:" + ioe.getMessage());
        }

        //插入数据
        try {
            srcImgUrl = imageService.getSrcImgUrl(deal.getId());
            Date nowDate = new Date();
            deal.setCreateTime(nowDate);
            deal.setUpdateTime(nowDate);
            deal.setImageUrl(srcImgUrl);
            deal.setPublishTime(nowDate);

            insCnt = dealDao.insertDeal(deal);
        } catch (Exception e) {
            ret = new ResultEntity(ResultEnum.EXC_DB, "添加失败，数据库异常");
            return ret;
        }

        if (insCnt == 0) {
            ret = new ResultEntity(ResultEnum.DEAL_ADD_FAIL_CHECK,"添加数据失败，id = " + deal.getId());
        } else {
            ret = new ResultEntity(ResultEnum.DEAL_ADD_SUCCESS,"添加数据成功， id = " + deal.getId());
        }
        //插入数据 end

        return ret;
    }

    @Override
    public ResultEntity deleteDeal(Long id) {
        if(id == null) {
            return new ResultEntity(ResultEnum.DEAL_ADD_FAIL_CHECK,"id为空");
        }

        //删除数量
        int dltCnt = -1;
        //处理结果实体
        ResultEntity resultEntity = null;

        try {
            dltCnt = dealDao.deleteById(id);
        } catch (Exception e) {
            resultEntity = new ResultEntity(ResultEnum.EXC_DB, "删除失败，数据库异常");
            return resultEntity;
        }

        if (dltCnt == 0) {
            resultEntity = new ResultEntity(ResultEnum.DEAL_DELETE_SUCCESS,"对应数据不存在，id = " + id);
        } else {
            resultEntity = new ResultEntity(ResultEnum.DEAL_DELETE_SUCCESS,"删除数据id = " + id);
        }

        return resultEntity;
    }

    @Override
    public ResultEntity editDeal(Deal deal, MultipartFile image) {
        ResultEntity ret = null;
        InputStream imageIn = null;
        int insCnt = 0;
        String srcImgUrl = null;
        //准备生成图
        if(image != null && !image.isEmpty()){
            try {
                imageIn = image.getInputStream();
                imageService.storeImage(deal.getId(), imageIn, IMAGE_MODULE);
                srcImgUrl = imageService.getSrcImgUrl(deal.getId());
            } catch (IOException ioe) {
                return new ResultEntity(ResultEnum.EXC_ELSE, "上传文件失败,程序错误:" + ioe.getMessage());
            }
        }

        //更新数据
        try {
            Date nowDate = new Date();
            deal.setUpdateTime(nowDate);
            deal.setImageUrl(srcImgUrl);
            deal.setPublishTime(nowDate);

            insCnt = dealDao.updateDealById(deal);
        } catch (Exception e) {
            ret = new ResultEntity(ResultEnum.EXC_DB, "修改失败，数据库异常");
            return ret;
        }

        if (insCnt == 0) {
            ret = new ResultEntity(ResultEnum.DEAL_ADD_FAIL_CHECK,"修改数据失败，id = " + deal.getId());
        } else {
            ret = new ResultEntity(ResultEnum.DEAL_ADD_SUCCESS,"修改数据成功， id = " + deal.getId());
        }
        //插入数据 end

        return ret;
    }

    @Override
    public ResultEntity genOrder(Long dealId, Order order) {
        ResultEntity ret = null;
        //check
        Deal deal = dealDao.selectById(dealId);
        if(deal == null || deal.getInventoryAmount() < order.getComamount() || deal.getVendibilityAmount() < order.getComamount()){
            return new ResultEntity(ResultEnum.DEAL_ORDER_FAIL_CHECK,"下单失败,id不存在，id = " + deal.getId());
        }

        order.setMerchantname(deal.getMerchantName());
        order.setMerchantress(deal.getMerchantAddress());
        int id = Integer.parseInt(deal.getId()+"");
        order.setCommodityid(id);
        boolean result = orderService.addOrder(order).getBody().getHttpStatus().equals(HttpStatus.OK);
        if(!result){
            return new ResultEntity(ResultEnum.EXC_REMOTE, "下单失败，接口异常");
        }

        HashMap<String, Object> map = new HashMap();
        map.put("amount", order.getComamount());
        map.put("updateTime", new Date());
        map.put("id", deal.getId());
        int retCol = dealDao.updateDealForOrder(map);

        return new ResultEntity(ResultEnum.DEAL_ORDER_SUCCESS,"下单成功， id = " + deal.getId());
    }
}
